from ihome.api_1_0 import api
from ihome import redis_store, db
from flask import request, jsonify, current_app, session
from ihome.utils.response_code import RET
from ihome.models import User
from sqlalchemy.exc import IntegrityError
from werkzeug.security import generate_password_hash, check_password_hash
import re


@api.route("/users", methods=["POST"])
def register():
    '''用户注册
    :param 手机号、短信验证码、密码、确认密码
    :return json
    '''
    # 获取参数
    req_dict = request.get_json()

    mobile = req_dict.get("mobile")
    sms_code = req_dict.get("sms_code")
    password = req_dict.get("password")
    password2 = req_dict.get("password2")

    # 检验参数
    if not all([mobile, sms_code, password, password2]):
        return jsonify(errno=RET.NODATA, errmsg="缺少参数")

    # 检验手机号
    if not re.match(r"1[34587]\d{9}", mobile):
        return jsonify(errno=RET.DATAERR, errmsg="手机号格式错误")

    # 密码是否相等
    if password != password2:
        return jsonify(errno=RET.NODATA, errmsg="两次密码不一致")

    # 从redis中取出短信密码
    try:
        real_sms_code = redis_store.get("send_sms_code_%s" % mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="验证码读取错误")

    # 判断验证码是否过期
    if real_sms_code is None:
        return jsonify(errno=RET.DBERR, errmsg="验证码已过期")

    # 删除验证码，防止重复验证
    try:
        redis_store.delete("send_sms_code_%s" % mobile)
    except Exception as e:
        current_app.logger.error(e)

    if real_sms_code != sms_code:
        return jsonify(errno=RET.DATAERR, errmsg="验证码输入错误")

    # 采用sha256 对密码加密保存到数据库中，md5,sha1加密已经被破解(暴力破解)，

    # 保存用户数据到数据库中
    user = User(name=mobile, mobile=mobile)
    # password函数作为属性被调用
    user.password = password
    try:
        db.session.add(user)
        db.session.commit()
    except IntegrityError as e:  # 重复错误
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="手机号已存在")
    except Exception as e:  # 其他错误
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="查询数据库异常")

    session["name"] = mobile
    session["mobile"] = mobile
    session["user_id"] = user.id

    return jsonify(errno=RET.OK, errmsg="注册成功")

